package org.maven.ide.eclipse.wtp.ext;

import org.apache.maven.project.MavenProject;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.maven.ide.eclipse.core.MavenLogger;
import org.maven.ide.eclipse.project.IMavenProjectFacade;
import org.maven.ide.eclipse.project.MavenProjectChangedEvent;
import org.maven.ide.eclipse.project.configurator.AbstractProjectConfigurator;
import org.maven.ide.eclipse.project.configurator.ProjectConfigurationRequest;
import org.maven.ide.eclipse.wtp.MarkedException;

/**
 * WTPExtProjectConfigurator
 * 
 * @author jer@printstacktrace.org
 */
public class WTPExtProjectConfigurator extends AbstractProjectConfigurator {

	  @Override
	  public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor)
	      throws CoreException {
	    MavenProject mavenProject = request.getMavenProject();
	    IProjectConfiguratorDelegate configuratorDelegate = ProjectConfiguratorDelegateFactory
	        .getProjectConfiguratorDelegate(mavenProject.getPackaging());
	    if(configuratorDelegate != null) {
	      IProject project = request.getProject();
	      try {
	        configuratorDelegate.configureProject(project, mavenProject, monitor);
	        configuratorDelegate.setModuleDependencies(project, mavenProject, monitor);
	      } catch(MarkedException ex) {
	        MavenLogger.log(ex.getMessage(), ex);
	      }
	    }
	  }

	  @Override
	  protected void mavenProjectChanged(MavenProjectChangedEvent event, IProgressMonitor monitor) throws CoreException {
	    IMavenProjectFacade facade = event.getMavenProject();
	    if(facade != null) {
	      IProject project = facade.getProject();
	      if(isWTPProject(project)) {
	        MavenProject mavenProject = facade.getMavenProject(monitor);
	        IProjectConfiguratorDelegate configuratorDelegate = ProjectConfiguratorDelegateFactory
	            .getProjectConfiguratorDelegate(mavenProject.getPackaging());
	        if(configuratorDelegate != null) {
	          configuratorDelegate.setModuleDependencies(project, mavenProject, monitor);
	        }
	      }
	    }
	  }

	  static boolean isWTPProject(IProject project) {
		  return ComponentCore.createComponent(project) != null;
	   // return ModuleCoreNature.getModuleCoreNature(project) != null;
	  }

}